/**
 * File    : OnEvent.java
 * Created : 2008-10-18
 * By      : LuHuiguo
 */
package com.luhuiguo.tapestry.mixins;

import java.util.List;

import org.apache.tapestry5.ClientElement;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.RenderSupport;
import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.IncludeJavaScriptLibrary;
import org.apache.tapestry5.annotations.InjectContainer;
import org.apache.tapestry5.annotations.MixinAfter;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;

/**
 * @author LuHuiguo
 * @version $Id: OnEvent.java 9 2008-10-18 13:47:15Z LuHuiguo $
 * 
 */
@IncludeJavaScriptLibrary(value = { "${tapestry.scriptaculous}/prototype.js",
		"OnEvent.js" })
@MixinAfter
public class OnEvent {

	@Inject
	private ComponentResources resources;

	@InjectContainer
	private ClientElement clientElement;

	@Parameter(required = true, defaultPrefix = "literal")
	private String event;

	@Parameter(required = false, defaultPrefix = "literal")
	private String onCompleteCallback;

	@Parameter(required = false, defaultPrefix = "literal")
	private boolean stop;

	@Parameter
	private List<?> context;

	@Environmental
	private RenderSupport pageRenderSupport;

	private Object[] contextArray;

	public String getEventName() {
		return event;
	}

	public List<?> getContext() {
		return context;
	}

	@SetupRender
	void setupRender() {
		contextArray = context == null ? new Object[0] : context.toArray();
	}

	@AfterRender
	void afterRender(MarkupWriter writer) {
		Link link = resources.createEventLink(getEventName().toLowerCase(),
				contextArray);
		String id = clientElement.getClientId();

		String jsString = "new OnEvent('%s', '%s', %b, '%s', '%s');";
		String callBackString = resources.isBound("onCompleteCallback") ? onCompleteCallback
				: "";
		boolean doStop = resources.isBound("stop") ? stop : false;

		pageRenderSupport.addScript(jsString, getEventName(), id, doStop, link
				.toAbsoluteURI(), callBackString);
	}

}